package com.tdzh.maimaiti.view;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.tdzh.maimaiti.R;
import com.tdzh.maimaiti.biz.GetContractList;
import com.tdzh.maimaiti.util.UriAPI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FriendsAppActivity extends AppCompatActivity {

    private ListView mAppList;
    private AsyncTask mGetAppTask;
    private String userphone;
    private List<Map<String, Object>> applierList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friends_app);

        SharedPreferences user = getSharedPreferences("account", 0);
        userphone = user.getString("name", null);

        mAppList = (ListView) findViewById(R.id.friendsAppList);

        mGetAppTask = new GetAppTask(userphone, UriAPI.HTTPApplication);
        mGetAppTask.execute((Void) null);

//        System.out.println("layout " + mAppList.getChildAt(0).toString());

    }

    public class GetAppTask extends AsyncTask {

        private final String mPhone;
        private final String mUrl;

        GetAppTask(String userPhone,String url) {
            mPhone = userPhone;
            mUrl = url;
        }

        @Override
        protected Object doInBackground(Object... params) {
            String result = "";
            //ArrayList list = params;
            //请求数据
            HttpPost httpRequest = new HttpPost(mUrl);
            byte[] data = new byte[2048];
//            System.out.println(mPhone);
            try {
                //创建参数

                //JSONArray jsonArray = new JSONArray(( (  (ArrayList<Map<String,Object>>) params[0]).toString()));
                List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                nameValuePair.add(new BasicNameValuePair("ContractList", "13269338058"));
                System.out.println("已启动 ");
                //对提交数据进行编码
                httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair
                        , HTTP.UTF_8));
                HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                //获取响应服务器的数据
                System.out.println("连接 " + httpResponse.getStatusLine().getStatusCode());
                if (httpResponse.getStatusLine().getStatusCode() == 200) {

                    //先把从服务端来的数据转化成字节数组
                    data = EntityUtils.toByteArray((HttpEntity) httpResponse.getEntity());
                    //再创建字节数组输入流对象
                    ByteArrayInputStream bais = new ByteArrayInputStream(data);
                    //绑定字节流和数据包装流
                    DataInputStream dis = new DataInputStream(bais);
                    //将字节数组中的数据还原成原来的各种数据类型，代码如下：
                    result = new String(dis.readUTF());
                    //inStream.close();
                    System.out.println( result);

                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(Object result) {
            mGetAppTask = null;
            applierList = new ArrayList<>();
            String r = result.toString();
            try {
                applierList = GetContractList.resolveContractsList(r);
            } catch (JSONException e) {
                e.printStackTrace();
            }


            if (applierList != null) {
                System.out.println("result " + r);

                SimpleAdapter adapter = new SimpleAdapter(FriendsAppActivity.this, applierList, R.layout.application_item_layout,
                        new String[]{"name", "phoneNumber", "image"},
                        new int[]{R.id.applierName, R.id.applierPhonenumber, R.id.applierImg});
                mAppList.setAdapter(adapter);
                System.out.println("fQ ");
                System.out.println("count " + mAppList.getCount());

               // for(int i = 0; i < mAppList.getCount(); i++) {
                    RelativeLayout layout = (RelativeLayout) mAppList.getAdapter().getView(0, null, mAppList);
                    System.out.println("layout " + layout.toString());
                    Button acceptButton = (Button) layout.findViewById(R.id.acceptFriends);
                    Button refuseButton = (Button) layout.findViewById(R.id.refuseFriends);
                    TextView phoneText = (TextView) layout.findViewById(R.id.applierPhonenumber);
                    System.out.println("button " + acceptButton.getText());

                    acceptButton.setOnClickListener(new myListener(phoneText.getText().toString(), "accept"));
                    phoneText.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            System.out.println("text ");
                        }
                    });
                    refuseButton.setOnClickListener(new myListener(phoneText.getText().toString(), "refuse"));
                    System.out.println("here ");

               // }
            } else{

                Toast.makeText(FriendsAppActivity.this, "获取失败", Toast.LENGTH_SHORT);
                //Intent intent = new Intent(MyP,);

            }
        }

    }

    private class AcceptFriendTask extends AsyncTask {

        private final String mPhone;
        private final String mUrl;
        private final String mMode;

        AcceptFriendTask(String userPhone,String mode, String url) {
            mPhone = userPhone;
            mUrl = url;
            mMode = mode;
        }

        @Override
        protected Object doInBackground(Object... params) {
            String result = "";
            //ArrayList list = params;
            //请求数据
            HttpPost httpRequest = new HttpPost(mUrl);
            byte[] data = new byte[2048];
           // System.out.println(mPhone);
            Map<String, String> res = new HashMap<String, String>();
            try {
                //创建参数

                //JSONArray jsonArray = new JSONArray(( (  (ArrayList<Map<String,Object>>) params[0]).toString()));
                List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                nameValuePair.add(new BasicNameValuePair("userPhone", "13269338058"));
                nameValuePair.add(new BasicNameValuePair("applyPhone", mPhone));
                nameValuePair.add(new BasicNameValuePair("mode", mMode));
                System.out.println("已启动 ");
                //对提交数据进行编码
                httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair
                        , HTTP.UTF_8));
                HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                //获取响应服务器的数据
                System.out.println("连接 " + httpResponse.getStatusLine().getStatusCode());
                if (httpResponse.getStatusLine().getStatusCode() == 200) {

                    //先把从服务端来的数据转化成字节数组
                    data = EntityUtils.toByteArray((HttpEntity) httpResponse.getEntity());
                    //再创建字节数组输入流对象
                    ByteArrayInputStream bais = new ByteArrayInputStream(data);
                    //绑定字节流和数据包装流
                    DataInputStream dis = new DataInputStream(bais);
                    //将字节数组中的数据还原成原来的各种数据类型，代码如下：
                    result = new String(dis.readUTF());
                    //inStream.close();
                    System.out.println("" + result);


                    res.put("result", result);
                    res.put("phone", mPhone);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return res;
        }

        @Override
        protected void onPostExecute(Object result) {
            mGetAppTask = null;
            Map<String, String> r = (HashMap<String, String>) result;
            if(r != null)
            {
                String status = r.get("result");
                if (status.equals("success"))
                {
                    for(int i = 0; i < applierList.size(); i ++) {
                        if(applierList.get(i).get("phoneNumber").equals(r.get("phone"))) {
                            applierList.remove(i);
                        }
                    }
                    ((SimpleAdapter) mAppList.getAdapter()).notifyDataSetChanged();
                } else
                {
                    Toast.makeText(FriendsAppActivity.this, "操作失败", Toast.LENGTH_SHORT);
                    return;
                }
            }
        }

    }

    private class myListener implements View.OnClickListener{

        String mPhone;
        String mode;
        private myListener(String phone, String mode){
            this.mPhone = phone;
            this.mode = mode;
        }
        @Override
        public void onClick(View v) {
            System.out.println("click ");
            new AcceptFriendTask(mPhone,UriAPI.HTTPAcceptAPP, this.mode).execute();
        }
    }


}
